<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\ArticleCateService;
use app\admin\service\ArticleService;
use app\admin\service\ArticleViewsService;
use app\admin\service\OfficialStaffService;
use app\admin\service\ResourceService;
use app\admin\validate\Article as ArticleValidate;
use app\admin\model\ArticleCate;
use app\admin\validate\ArticleCate as ArticleCateValidate;
use app\AdminController;
use think\exception\ValidateException;

class Lore extends AdminController
{
    /**
     * 企业微信
     * @param int $source
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($source = 1)
    {
        // 1企业微信  2社群知识  3社群案例
        $sourceName = getArticleCateName($source);
        $where[] = ['types', '=', $source];
        $user_auth = session('user_auth');
        // 登录账号是？？？
        // 超管、管理员
        if (in_array($user_auth['role'], [1, 6])) {
            // 默认查询全部
            $manager = intval($this->request->param('manager', 0));
            // 查询对应的登录用户数据
        } else {
            // 获取涨知识人员id
            $manager = intval($user_auth['manager']);
        }
        // 涨知识工作人员
        $officialStaff = OfficialStaffService::getOfficialStaff(2);

        // 查询某工作人员下的用户数据
        $access['otherArticleView'] = $access['articleViewsLine'] = 0;
        if ($manager) {
            $view = 'user_index';
            $where[] = ['enroll_id', '=', $manager];
            // 当前分类文章访问总数
            $access['currentArticleViews'] = ArticleViewsService::countArticleViews($where);
            // 提成点
            $branch['commission_ratio'] = OfficialStaffService::findOfficialStaffValue(['id' => $manager], 'commission_ratio');
            $currentArticleViews = $access['currentArticleViews'];

            // 这里是全部
        } else {
            $view = 'index';
            // 文章访问总数
            $access['totalArticleViews'] = ArticleViewsService::countArticleViews();
            // 文章访问总数（折线图）
            $access['articleViewsLine'] = ArticleViewsService::getArticleViewsLine();
            // 当前分类文章访问总数、用户分配
            $access['currentArticleViews'] = ArticleViewsService::getArticleViewsPeople(['types', '=', $source]);
            // 其他分类文章访问总数
            $access['otherArticleView'] = ArticleViewsService::getOtherArticleViewPeople([['types', '<>', $source]]);
            // 提成点（先恒定全部人都是这个）
            $branch['commission_ratio'] = 0.1;
            $currentArticleViews = $access['currentArticleViews']['viewNums'];
        }
        // 当前分类文章访问总数（折线图）
        $access['currentArticleViewsLine'] = ArticleViewsService::getArticleViewsLine($where);
        // 当月总访问
        $branch['monthArticleView'] = ArticleViewsService::countMonthArticlePeopleViews($where);
        // 所得佣金
        $branch['commission'] = sprintf("%.2f", $currentArticleViews * $branch['commission_ratio']);
        // 文章总数
        $branch['totalArticle'] = ArticleService::countArticle($where);
        // 实时访问量
        $branch['todayArticleViews'] = ArticleViewsService::countTodayArticlePeopleViews($where);
        $branch['yesTodayArticleViews'] = ArticleViewsService::countYesTodayArticlePeopleViews($where);
        // 本月新增文章
        $branch['monthCreateArticle'] = ArticleService::countArticleMonthCreate($where);

        // 访问人身份数据
        $identityArticleData = ArticleViewsService::getIdentityArticleData($where);

        if (request()->isPost()) {
            $keywords = trim(input('keywords', ''));
            if (!empty($keywords)) {
                $where[] = ['title', 'like', '%' . $keywords . '%'];
            }

            $list = ArticleService::getArticleList($where, $this->page, $this->pagesize);
            $count = ArticleService::countArticleList($where);

            return adminResponseJson(['source' => $source, 'list' => $list, 'count' => $count]);
        }

        return view($view, [
            'source' => $source,
            'sourceName' => $sourceName,
            'manager' => $manager,
            'access' => $access,
            'branch' => $branch,
            'action' => $this->request->action(),
            'officialStaff' => $officialStaff,
            'userRole' => $user_auth['role'],
            'identityArticleData' => $identityArticleData,
        ]);
    }

    /**
     * 社群知识
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function knowledge()
    {
        return $this->index(2);
    }

    /**
     * 社群知识添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function knowledgeAdd()
    {
        return $this->loreAdd(2);
    }

    /**
     * 社群知识编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function knowledgeEdit()
    {
        return $this->loreEdit(2);
    }

    /**
     * 社群知识状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function knowledgeChangeStatus()
    {
        return $this->changeStatus(2);
    }

    /**
     * 社群案例
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function caseStudy()
    {
        return $this->index(3);
    }

    /**
     * 社群案例添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function caseStudyAdd()
    {
        return $this->loreAdd(3);
    }

    /**
     * 社群案例编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function caseStudyEdit()
    {
        return $this->loreEdit(3);
    }

    /**
     * 社群案例状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function caseStudyChangeStatus()
    {
        return $this->changeStatus(3);
    }

    /**
     * 涨知识添加
     * @param int $source
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loreAdd($source = 1)
    {
        switch ($source) {
            case 2:
                $action = 'knowledge';
                $form = 'knowledgeAdd';
                break;
            case 3:
                $action = 'caseStudy';
                $form = 'caseStudyAdd';
                break;
            default:
                $action = 'index';
                $form = 'loreAdd';
        }
        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(ArticleValidate::class)->sceneInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if ($data['rid']) {
                $resource = ResourceService::findResource(['id' => $data['rid'], 'status' => 1]);
                if (!$resource) {
                    $this->error(adminJsonMsg(10014));
                }
            }

            $data['key'] = md5($data['title']);
            $info = ArticleService::findArticle(['key' => $data['key']]);
            if ($info) {
                $this->error(adminJsonMsg(10015));
            }

            $data['is_pay'] = isset($data['money']) && $data['money'] > 0 ? 1 : 0;
            $res = ArticleService::createArticle($data);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            // 存储文件到阿里云
            $addPath[] = $data['cover'];
            AliOosService::uploadAliOos($addPath);

            $this->success(adminJsonMsg(1004), (STRING)url('/lore/' . $action));
        }

        // 涨知识分类
        $topCate = ArticleCateService::getAllArticleCate();
        // 发布人
        $officialStaff = OfficialStaffService::getOfficialStaff();

        return view('lore_add', [
            'topCate' => $topCate,
            'officialStaff' => $officialStaff,
            'source' => $source,
            'form' => (STRING)url('/lore/' . $form)
        ]);
    }

    /**
     * 涨知识编辑
     * @param int $source
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loreEdit($source = 1)
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $info = ArticleService::findArticle(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        switch ($source) {
            case 2:
                $action = 'knowledge';
                $form = 'knowledgeEdit';
                break;
            case 3:
                $action = 'caseStudy';
                $form = 'caseStudyEdit';
                break;
            default:
                $action = 'index';
                $form = 'loreEdit';
        }

        $info['ycover'] = config('url.url') . $info['cover'];

        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(ArticleValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if ($data['rid']) {
                $resource = ResourceService::findResource(['id' => $data['rid'], 'status' => 1]);
                if (!$resource) {
                    $this->error('该社群ID不存在');
                }
            }

            $data['key'] = md5($data['title']);
            $data['is_pay'] = isset($data['money']) && $data['money'] > 0 ? 1 : 0;
            $res = ArticleService::updateArticle($data, ['id' => $data['id']]);
            if (!$res) {
                $this->error('操作失败');
            }

            $delPath = [];
            $addPath = [];

            // 更改了封面
            if ($data['cover'] != $info['cover']) {
                $delPath[] = $info['cover'];
                $addPath[] = $data['cover'];
            }

            AliOosService::uploadAliOos($addPath);

            // 删除封面
            if ($delPath) {
                foreach ($delPath as $path) {
                    Upload::delImageOrVideo($path);
                }
            }

            $this->success(adminJsonMsg(1004), (STRING)url('/lore/' . $action));
        }

        // 知识分类
        $topCate = ArticleCateService::getAllArticleCate();
        // 发布人
        $officialStaff = OfficialStaffService::getOfficialStaff();

        return view('lore_edit', [
            'info' => $info,
            'topCate' => $topCate,
            'officialStaff' => $officialStaff,
            'source' => $source,
            'form' => (STRING)url('/lore/' . $form)
        ]);
    }

    /**
     * 状态修改
     * @param int $mode 0涨知识  1分类
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus($mode = 0)
    {
        $id = intval($this->request->param('id', 0));
        $type = intval($this->request->param('type', 0));
        $field = trim($this->request->param('field', 'status'));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $where = ['id' => $id];
        if (!$mode) {
            $info = ArticleService::findArticle($where);
        } else {
            $info = ArticleCateService::findArticleCate($where);
        }
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        // 删除
        if (!$type) {
            $changeFields = -1;
            // 状态修改
        } else {
            $changeFields = $info[$field] == 1 ? 0 : 1;
        }

        if (!$mode) {
            $result = ArticleService::updateArticle([$field => $changeFields], $where);
        } else {
            $isExists = ArticleService::findArticle(['cids' => $id]);
            if ($isExists) {
                $this->error(adminJsonMsg(10016));
            }
            $result = ArticleCateService::updateArticleCate([$field => $changeFields], $where);
        }

        if (!$result) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }

    /**
     * 涨知识分类
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loreCate()
    {
        if (request()->isPost()) {
            $where = [];
            $keywords = trim(input('keywords', ''));
            if (!empty($keywords)) {
                $where[] = ['name', 'like', '%' . $keywords . '%'];
            }

            $list = ArticleCateService::getArticleCateList($where, $this->page, $this->pagesize);
            $count = ArticleCateService::countArticleCateList($where);
            return adminResponseJson(['list' => $list, 'count' => $count]);
        }
        return view();
    }

    /**
     * 涨知识分类添加/编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loreCateEdit()
    {
        $id = intval($this->request->param('id', 0));
        // 默认 “添加”
        $info = new ArticleCate();
        $scene = 'insert';
        if ($id) {
            $info = ArticleCateService::findArticleCate(['id' => $id]);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }
            $scene = 'edit';
        }

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(ArticleCateValidate::class)->scene($scene)->check($data);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getError());
            }

            if ($data['id']) {
                ArticleCateService::updateArticleCate($data, ['id' => $data['id']]);
            } else {
                ArticleCateService::createArticleCate($data);
            }

            $this->success(adminJsonMsg(1004), (STRING)url('/lore/loreCate'));
        }

        return view('', ['info' => $info]);
    }

    /**
     * 涨知识分类删除
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loreCateDel()
    {
        return $this->changeStatus(1);
    }
}